package com.honghu.villagepost.activity.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import com.ada.common.util.CollectionUtil
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ObjectUtils
import com.honghu.villagepost.R
import com.honghu.villagepost.activity.ContactUsActivity
import com.honghu.villagepost.activity.GoodsCidListActivity
import com.honghu.villagepost.activity.SearchActivity
import com.honghu.villagepost.activity.StoreDetailsActivity
import com.honghu.villagepost.adapter.ClassifyAdapter
import com.honghu.villagepost.adapter.ImageAdapter
import com.honghu.villagepost.adapter.MarqueeViewAdapter
import com.honghu.villagepost.adapter.StoreAdapter
import com.honghu.villagepost.api.ApiService
import com.honghu.villagepost.base.BaseFragment
import com.honghu.villagepost.callback.DialogCallback
import com.honghu.villagepost.callback.LzyResponse
import com.honghu.villagepost.constant.IntentKeyConstant
import com.honghu.villagepost.entity.BannerEntity
import com.honghu.villagepost.entity.Classify
import com.honghu.villagepost.entity.Store
import com.lzy.okgo.model.Response
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.wuhenzhizao.sku.utils.ScreenUtils
import com.youth.banner.indicator.CircleIndicator
import kotlinx.android.synthetic.main.fragment_city.*


/**
 * @author: mqwang
 * @create: 1/26/21 10:19 AM
 * @Description: 逛城市fragment
 */
class CityFragment : BaseFragment() {

    private val storeAdapter: StoreAdapter by lazy {
        StoreAdapter()
    }

    private val classifyAdapter: ClassifyAdapter by lazy {
        ClassifyAdapter()
    }

    private val imageAdapter: ImageAdapter by lazy {
        ImageAdapter(bannerEntities)
    }

    private val bannerEntities: MutableList<BannerEntity> = ArrayList()

    private var page = 1
    private val shopType = 2

    override fun initViews(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val view = inflater!!.inflate(R.layout.fragment_city, container, false)
        return view
    }

    override fun initData() {
        val statusBarHeight = ScreenUtils.getStatusBarHeight(activity)
        root_layout.setPadding(0, statusBarHeight, 0, 0)

        fl_search.setOnClickListener {
            ActivityUtils.startActivity(SearchActivity::class.java)
        }

        iv_msg.setOnClickListener {
            ActivityUtils.startActivity(ContactUsActivity::class.java)
        }

        rv_classify.adapter = classifyAdapter
        rv_classify.layoutManager = GridLayoutManager(activity, 5)
        rv_list.adapter = storeAdapter

        val bannerEntity = BannerEntity()
        bannerEntity.picRes = R.mipmap.ic_banner_city
        bannerEntities.add(bannerEntity)
        banner.adapter = imageAdapter
        banner.addBannerLifecycleObserver(this)
        banner.indicator = CircleIndicator(activity)
        imageAdapter.notifyDataSetChanged()

        val data: MutableList<String> = ArrayList()
        data.add("神奇宝贝（精灵宝可梦）有哪些著名的梗？")
        data.add("我翻开自我保护的书，上面只写了两个大字：证据")
        data.add("接纳自己，是无条件地爱，包括爱所有的痛苦")
        data.add("3 岁前，世界对待孩子的一切，都会给他们留下深刻的第一印象")
        data.add("担心今天没锻炼，现在站起来，做一组完美深蹲")

        marquee_view?.setAdapter(MarqueeViewAdapter(data, activity))
        //刷新数据
        //marqueeViewAdapter.setData(data);

        storeAdapter.setOnItemClickListener { adapter, view, position ->
            var store = adapter.getItem(position) as Store
            StoreDetailsActivity.self(activity!!, store.id, 0)
        }

        classifyAdapter.setOnItemClickListener { adapter, view, position ->
            var goods = adapter.getItem(position) as Classify
            GoodsCidListActivity.self(activity!!, goods.id, goods.name)
        }

        smart_refresh.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                onRefreshData()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                loadData()
            }

        })

        getData()
        onRefreshData()
    }

    private fun onRefreshData() {
        page = 1
        loadData()
    }

    fun getData() {
        ApiService.goods_category(this, shopType, object : DialogCallback<LzyResponse<List<Classify>>>() {
            override fun onSuccess(response: Response<LzyResponse<List<Classify>>>?) {
                classifyAdapter.setNewData(response!!.body().data)
            }
        })
    }

    fun loadData() {
        ApiService.shop_list(this, shopType, page, object : DialogCallback<LzyResponse<Store>>() {
            override fun onSuccess(response: Response<LzyResponse<Store>>?) {
                val records = response!!.body().data.records
                onGetDataSuc(records)
            }

        })
    }

    /**
     * 拉取数据成功时调用
     * @param data 数据源
     */
    protected fun onGetDataSuc(data: List<Store>) {
        finishRefresh(smart_refresh)
        bindData(isRefresh(), data)
        if (!ObjectUtils.isEmpty(data)) {
            page++
        }
        if (CollectionUtil.getSize(data) < IntentKeyConstant.PAGE_COUNT) { //无更多
            smart_refresh.setNoMoreData(true) //将不会再次触发加载更多事件
        } else {
            smart_refresh.setNoMoreData(false) //还有更多
        }
    }

    fun bindData(isRefresh: Boolean, list: List<Store>) {
        if (isRefresh) {
            storeAdapter.setNewData(list)
        } else {
            storeAdapter.addData(list)
        }
    }

    private fun isRefresh(): Boolean {
        return page == 1
    }
}